package com.ssca.redis;

import java.io.IOException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FtpClient {
	private static String IP = "192.168.1.184";
	private static String USER = "taseUser";
	private static String PWD = "62283748";

	private static Logger logger = LogManager.getLogger();

	FTPClient ftpClient = new FTPClient();

	@SuppressWarnings("unused")
	public void getFileListSet(String remoteFileRoot, List<String> fileList) {
		if (!ftpClient.isAvailable() || !ftpClient.isConnected()) {
			initialFtpClient();
		}
		int reply = ftpClient.getReplyCode();

		try {
			logger.info("\t" + remoteFileRoot);
			ftpClient.changeWorkingDirectory(remoteFileRoot);
			FTPFile[] files = ftpClient.listFiles();
			for (FTPFile file : files) {
				if (!file.isDirectory()) {
					if (file.getName().endsWith(".apk")) {
						// JedisUtil.lpush("ftp4wormhole", remoteFileRoot + "/"
						// + file.getName());
						// JedisUtil.lpush("aaaa", remoteFileRoot + "/" +
						// file.getName());
						fileList.add(remoteFileRoot + "/" + file.getName());
						// System.out.println(remoteFileRoot + "/" +
						// file.getName());
						// logger.info("\t" + remoteFileRoot + "/" +
						// file.getName());
					}
				} else {
					getFileListSet(remoteFileRoot + "/" + file.getName(), fileList);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				ftpClient.disconnect();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void initialFtpClient() {
		try {
			ftpClient.connect(IP);
			ftpClient.login(USER, PWD);
		} catch (SocketException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		// new FtpClient().getFileList(args[0]);
		// new FtpClient().getFileList("/analysis/apk");
		List<String> fileList = new ArrayList<String>();
		new FtpClient().getFileListSet("/analysis2/playdrone/apk", fileList);
		Map<String, String> fileMap = new HashMap<String, String>();
		for (String path : fileList) {
			String pkgName = path.substring(path.lastIndexOf("/") + 1, path.lastIndexOf("-"));
			fileMap.put(pkgName, path);
		}
		Iterator<Map.Entry<String, String>> entries = fileMap.entrySet().iterator();
		while (entries.hasNext()) {
			Map.Entry<String, String> entry = entries.next();
			String filePath = entry.getValue();
			JedisUtil.lpush("ftp_file", filePath);
		}
	}
}
